const slime_core   = require("../../annotation/index.js");
const events       = slime_core.events;


// TODO
@heard("slime.member_merged").then(function(mew) {

    let wrapper = mew.content["slime.member_merged"];

    @lab(function(lab) {
        return @.async.all(@.keys(events), function(group) {
            // TODO : 这个地方应该和ES同步
            @.async.all(@.keys(events[group].events), function(event) {
                let key = group + "_" + event + "_events"
                return lab.sqlite.query(`update ${key} set member_id = ? where member_id = ?`, wrapper.mainMember.id, wrapper.targetMember.id);
            }).pipe(this);
        })
    }).rejected(function(error) {
        @error(error);
    })
});


module.exports = function(lab) {
    return {
        "@getEventConfig" : function () {
            return JSON.parse(JSON.stringify(events));
        },
        "@createEvent": function(form) {
            let { group, event } = form
            if (events[group] && events[group].events[event]) {

                let createForm = {}
                let fields = [];

                if (events[group].events[event].fields) {
                    fields = Object.keys(events[group].events[event].fields)
                }

                fields = fields.concat(["ouid", "member_id", "event_source", "source_event_id", "source_event_date"])
                fields.forEach(function(key) {
                    createForm[key] = form[key]
                })

                createForm.create_date = Date.now();

                return lab.create(`${group}_${event}_events`, createForm);

            } else {
                throw @lab.errors.event_not_found;
            }
        },
        "@getEvents": function({ member_id, group, event, start_date }) {
            if (!member_id) {
                throw @lab.errors.event_not_found
            }
            let db_tables = []
            if (group && events[group]) {
                if (event && events[group].events[event]) {
                    db_tables.push({
                        group,
                        event
                    })
                } else {
                    Object.keys(events[group].events).forEach(function(key) {
                        db_tables.push({
                            group,
                            event: key
                        })
                    })
                }
            } else {
                Object.keys(events).forEach(function(key1) {
                    Object.keys(events[key1].events).forEach(function(key2) {
                        db_tables.push({
                            group: key1,
                            event: key2
                        })
                    })
                })
            }
            let result = {}
            return @.async.all(db_tables, function(target) {
                var conditions = ["member_id = ?"]
                var params = [member_id]
                if (start_date) {
                    conditions.push("create_date > ?")
                    params.push(start_date)
                }
                return lab.query(
                    [
                        `${target.group}_${target.event}_events`
                    ], {
                        conditions,
                        params,
                        sort: "create_date desc"
                    }).then(function({ list }) {
                    if (!result[target.group]) {
                        result[target.group] = {}
                    }
                    result[target.group][target.event] = list
                    this.next()
                })
            }).resolve(result)
        },
        "@listEvents": function({ member_id, group, event, start = 0, limit = 10 }) {
            if (!member_id || !group || !event || !events[group] || events[group].events[event]) {
                throw @lab.errors.event_not_found;
            }
            return lab.query(
                [
                    `${group}_${event}_events`
                ], {
                    start: start,
                    limit: limit,
                    conditions: ["member_id = ?"],
                    params: [member_id],
                    sort: "create_date desc"
                })
        }
    }
}